package com.cbh.amadeus.client.config;

import com.cbh.amadeus.client.annotation.AmadeusMessageRegister;
import com.cbh.amadeus.client.annotation.EnableAmadeusMessageSubscriber;
import com.cbh.amadeus.common.utils.StringPool;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.Map;
import java.util.Set;

/**
 * @author ChenBiHui
 * @date 2025/5/19
 */
public class AmadeusMessageRegisterImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                metadata.getAnnotationAttributes(EnableAmadeusMessageSubscriber.class.getName())
        );
        if (attributes == null) {
            throw new IllegalStateException("Can't find @EnableAmadeusMessageSubscriber");
        }
        String[] scan = attributes.getStringArray("scan");
        if (scan.length == 0) {
            String from = metadata.getClassName();
            scan = new String[1];
            scan[0] = from.substring(0, from.lastIndexOf(StringPool.DOT));
        }
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(AmadeusMessageRegister.class));
        scanner.setBeanNameGenerator(new AnnotationBeanNameGenerator() {
            @Override
            protected boolean isStereotypeWithNameValue(String annotationType, Set<String> metaAnnotationTypes, Map<String, Object> attributes) {
                return super.isStereotypeWithNameValue(annotationType, metaAnnotationTypes, attributes)
                        || "com.cbh.amadeus.client.annotation.AmadeusMessageRegister".equals(annotationType)
                        || metaAnnotationTypes.contains("com.cbh.amadeus.client.annotation.AmadeusMessageRegister");
            }
        });
        scanner.scan(scan);
    }
}
